#include "log_api.h"
#include "rfid_app.h"
//#include "sound_app.h"
//#include "ml307_app.h"
//#include "tp1107_app.h"
//#include "gtx31x_app.h"
#include "memroy_app.h"
//#include "safety_app.h"
#include "flash_board.h"
#include "event_board.h"
//#include "battery_app.h"
//#include "network_app.h"
#include "protocol_api.h"
#include "protocol_app.h"
#include "real_time_app.h"
#include "bluetooth_app.h"
#include "cardholder_api.h"
#include "device_parameter.h"

/**
 * @brief 事件中心任务回调
 *
 */
static uint16_t EventCenterTaskCallback(uint8_t TaskId, uint16_t Events);

static uint8_t EventCenterTaskHandle = 0;
static EventCenterExternalInterfaces_t EventCenterExternalInterfaces = {0};

static uint16_t EventCenterTaskCallback(uint8_t TaskId, uint16_t Events)
{
  if (TaskId == EventCenterTaskHandle)
  {
    if (Events & SYS_EVENT_MSG)
    {
      uint8_t *pMessage = tmos_msg_receive(EventCenterTaskHandle);
      if (pMessage != NULL)
      {
        tmos_msg_deallocate(pMessage);
      }

      return (Events ^ SYS_EVENT_MSG);
    }

    if (Events & TASK_SCHEDULE)
    {
      if (EventCenterExternalInterfaces.TaskSchedule != NULL)
      {
        EventCenterExternalInterfaces.TaskSchedule();
      }

      return (Events ^ TASK_SCHEDULE);
    }

    if (Events & SCHEDULED_TASK)
    {
      if (EventCenterExternalInterfaces.ScheduledTask != NULL)
      {
        EventCenterExternalInterfaces.ScheduledTask();
      }

      return (Events ^ SCHEDULED_TASK);
    }

    if (Events & DEVICE_REBOOT_LISTER)
    {
      if (EventCenterExternalInterfaces.DeviceRebootTask != NULL)
      {
        EventCenterExternalInterfaces.DeviceRebootTask();
      }

      return (Events ^ DEVICE_REBOOT_LISTER);
    }

    if (Events & RESTORE_RESULT_LISTER)
    {
      if (EventCenterExternalInterfaces.RestoreFactoryTask != NULL)
      {
        EventCenterExternalInterfaces.RestoreFactoryTask();
      }

      return (Events ^ RESTORE_RESULT_LISTER);
    }

    if (Events & SYSTEM_FIRMWARE_UPDATE)
    {
      if (EventCenterExternalInterfaces.FirmwareUpdateTask != NULL)
      {
        EventCenterExternalInterfaces.FirmwareUpdateTask();
      }

      return (Events ^ SYSTEM_FIRMWARE_UPDATE);
    }

    if (Events & DEVICE_SELF_TEST_LISTER)
    {
      if (EventCenterExternalInterfaces.DeviceSelfTestTask != NULL)
      {
        EventCenterExternalInterfaces.DeviceSelfTestTask();
      }

      return (Events ^ DEVICE_SELF_TEST_LISTER);
    }
  }

  return 0;
}

void EventDelayMs(uint32_t Ms)
{
  DelayMs(Ms);
}

void EventRealTimeInitialization(void)
{
  RealTimeInitialization();
}

uint32_t EventGetCurrectTimestamp(void)
{
  return RealTimeMakeCurrentTimestamp();
}

bool EventGetRfidFunctionEnable(void)
{
  return _RFID_FUNCTION_ENABLE_;
}

bool EventGetKeyboardFunctionEnable(void)
{
 return _KEYBOARD_FUNCTION_ENABLE_;
}

bool EventGetSafetyFunctionEnable(void)
{
 return _SAFETY_VERIFYFUNCTION_ENABLE_;
}

bool EventGetNetwokFunctionEnable(void)
{
 return _NETWOK_FUNCTION_ENABLE_;
}

bool EventGetSleepFunctionEnable(void)
{
  return HAL_SLEEP;
}

bool EventGetBatteryFunctionEnableBit(void)
{
//  if (_BOARD_TYPE_ != _9905_B_BOARD_)
//    return true;

  return false;
}

bool EventGetExternalValidationFunctionEnableBit(void)
{
 return _EXTERNAL_VALIDATION_EN_;
}

bool EventGetDayBroadcastContorlEn(void)
{
  return GetDayBroadcastContorlEn();
}

uint8_t EventGetBroadcastRemainingDays(void)
{
  return GetBroadcastRemainingDays();
}

uint8_t EventGetNormalOpenTipInterval(void)
{
  return GetNormalOpenReminderInterval();
}

uint16_t EventGetHeartbeatReportingInterval(void)
{
  return GetHeartbeatTransmissionCycle();
}

uint8_t EventUserActionTimeout(void)
{
  return GetSearchTimeout();
}

uint8_t EventRegisterTimeout(void)
{
  return (GetSearchTimeout() + REGISTER_TIME_BASED_COMPENSATION);
}

bool EventGetWhetherTheClutchIsClosed(void)
{
//  MotorLockStatus_t ClutchStaus = GetMotorActionStatus();

 // if (ClutchStaus != MOTOR_UNLOCKING)
 //   return true;

  return false;
}

bool EventGetHeadTongueAlarmIsTigger(void)
{
//  return GetHeadTongueTiggerEn();
}

bool EventGetFlaseLockAlarmEn(void)
{
//  return GetFlaseLockAlarmEn();
}

bool EventGetAntiPickingAlarmEn(void)
{
//  return GetAntiPickingAlarmEn();
}

bool EventGetLockedInEn(void)
{
//  return GetAntiLockSignalTiggerEn();
}

bool EventGetObliqueTongueTiggerEn(void)
{
//  return GetObliqueLockAlarmEn();
}

bool EventGetDoorNormalOpenEn(void)
{
//  if (GetMotorActionStatus() == MOTOR_NORMALLY_OPEN)
//    return true;

  return false;
}

uint8_t EventGetLockedInReminderInterval(void)
{
  return GetLockedInReminderInterval();
}

uint8_t EventGetNormalOpenReminderInterval(void)
{
  return GetNormalOpenReminderInterval();
}

uint8_t EventGetFalseLockAlarmAlertInterval(void)
{
  return GetFalseLockDetcetionInterval();
}

uint8_t EventGetTheBreakInAlarmAlertInterval(void)
{
  return GetTheBreakInDetcetionInterval();
}

bool EventGetSafatyModuleIdleEn(void)
{
//  if (SafetyGetDeviceActiveEn() == false)
//    return true;

  return false;
}

bool EventGetNetworkModuleIdleEn(void)
{
//  if (NetworkGetBusyEn() == false)
//    return true;

  return false;
}

bool EventGetDeviceActivationStatus(void)
{
  uint8_t DeviceInitStatus = GetDeviceInitStatus() & (~FIRMWARE_UPGRADE);
  if (DeviceInitStatus == NORMAL_MODE)
    return true;

  return false;
}

void EventFlagFirmwareUpdateEnable(void)
{
  uint8_t DeviceInitStatus = GetDeviceInitStatus();

  SetDeviceInitStatus(DeviceInitStatus | FIRMWARE_UPGRADE);
  MemoryUpdateDeviceParametersNoWait();
}

bool EventGetAuthorizationExpirationEn(void)
{
  uint32_t AuthorizationEndTime = GetAuthorizationEndTime();

  if (AuthorizationEndTime != 0)
  {
    uint32_t NowTimestamp = EventGetCurrectTimestamp();

    if (NowTimestamp >= AuthorizationEndTime)
      return true;
  }

  return false;
}

uint8_t EventGetUnlockTime(void)
{
  return GetUnlockTime();
}

uint32_t EventGetDeviceLastActionTime(void)
{
  return GetDeviceLastActionTime();
}

void EventSetDeviceLastActionTime(uint32_t LastActionTime)
{
  SetDeviceLastActionTime(LastActionTime);
  MemoryUpdateDeviceParameters();
}

uint8_t EventGetDeviceStandbyTime(void)
{
  return GetBluetoothConnectionTimeout();
}

SelfTestStartResult_t EventStartRfidSelfTest(void)
{
  if (RfidStartDeviceSelfTestTask() == true)
    return SELF_TEST_START_SUCCESS;

  return SELF_TEST_START_ERROR;
}

SelfTestStartResult_t EventStartKeyboardSelfTest(void)
{
 /// if (Gtx31xStartDeviceSelfTestTask() == true)
 //   return SELF_TEST_START_SUCCESS;

  return SELF_TEST_START_ERROR;
}

SelfTestStartResult_t EventStartSafetySelfTest(void)
{
//  if (SafetyStartDeviceSelfTestTask() == true)
//    return SELF_TEST_START_SUCCESS;

  return SELF_TEST_START_ERROR;
}

SelfTestStartResult_t EventStartNetworkSelfTest(void)
{
#if _BOARD_TYPE_ != _9905_B_BOARD_
//  if (NetworkInitiateSelfTestTask() == true)
    return SELF_TEST_START_SUCCESS;

  return SELF_TEST_START_ERROR;
#else
  return SELF_TEST_NO_SUPPORT;
#endif
}

ResetStartResult_t EventStartSafetyReset(void)
{
#if _BOARD_TYPE_ != _9905_B_BOARD_
//  if (SafetyStartDeviceFactorySettingTask() == true)
//    return RESET_START_SUCCESS;

  return RESET_START_ERROR;
#else
  return RESET_NO_SUPPORT;
#endif
}

ResetStartResult_t EventStartNetworkReset(void)
{
#if ((_BOARD_TYPE_ != _9905_B_BOARD_) && (_NETWOK_MODLE_TYPE_ == _TP1107_MODULE_))
//  if (NetworkInitiateDeviceResetTask() == true)
//    return RESET_START_SUCCESS;

  return RESET_START_ERROR;
#else
  return RESET_NO_SUPPORT;
#endif
}

bool EventStartRfidLocalRegister(void)
{
  return RfidStartLocalRegisterUserTask();
}

bool EventStartKeyboardLocalRegister(void)
{
//  return Gtx31xStartLocalRegisterTask();
}

bool EventStartSafetyLocalRegister(void)
{
//  return SafetyStartLocalRegisterUserTask();
}

bool EventStartReadCardTask(void)
{
  return RfidStartReadCardDataTask();
}

void EventStartKeyboardLocalRegisterExitListerTask(void)
{
//  Gtx31xLocalRegisterExitListerConfig();
}

void EventResetNetworkStatus(void)
{
//  NetworkResetWorkingStatus();
}

uint8_t EventGetVoltagePercentage(void)
{
//  return BatteryGetVoltagePercentage();
}

void EventKeyboardIntoSleepMode(void)
{
//  Gtx31xIntoSleepMode();
}

void EventKeyboardIntoStandbyMode(void)
{
//  Gtx31xIntoStandbyMode();
}

void EventStartKeyInAdminPasswordMode(void)
{
//  Gtx31xStartKeyInAdminPassword();
}

void EventKeyboardIntoVerifyUserPermissionMode(void)
{
//  Gtx31xVerifyUserPermissionTask();
}

void EventPlayExitDeviceLockedState(void)
{
//  PromptExitDeviceLockedState();
}

void EventPlayDeviceLocked(void)
{
//  PromptDeviceIsInLockedState();
}

void EventPlayStartDevSelfTest(void)
{
//  PromptStartDeviceSelfTest();
}

void EventPlayExitDevSelfTest(void)
{
//  PromptExitDeviceSelfTest();
}

void EventPlayExitOnlineRegisterMode(void)
{
//  PromptExitOnlineRegisterUser();
}

void EventPlayStartUserTypedKey(void)
{
//  PromptUserKeyedKeys();
}

void EventPlayExitKeyEntry(void)
{
//  PromptExitKeyEntry();
}

void EventPlayDoorNormalOpen(void)
{
//  PromptNormalOpenTigger();
}

void EventPlayExitSafetyModuleAuthentication(void)
{
//  PromptExitSafetyModuleAuthentication();
}

void EventPlayStartSafetyModuleAuthentication(void)
{
//  PromptStartSafetyModuleAuthentication();
}

void EventPlayExitLocalRegistration(void)
{
//  PromptExitLocalRegistration();
}

void EventPlayStartLocalRegistration(void)
{
//  PromptStartLocalRegistration();
}

void EventPlayKeyInstall(void)
{
//  PromptKeyInserted();
}

void EventPlayKeyRemove(void)
{
//  PromptKeyRemove();
}

void EventPlayAutiPickingTigger(void)
{
//  PromptAntiPickingAlarm();
}

void EventPlayAutiPickingRecovered(void)
{
//  PromptAntiPickingRecovered();
}

void EventPlayNormalOpenTigger(void)
{
//  PromptNormalOpenTigger();
}

void EventPlayNormalOpenRecovered(void)
{
//  PromptNormalOpenRecovered();
}

void EventPlayFalseLockAlarmTigger(void)
{
//  PromptFalseLockTigger();
//  PlayDoorNotCloseAudio();
}

void EventPlayFalseLockAlarmRecovered(void)
{
//  PromptFalseLockAlarmRecovered();
}

void EventPlayLockedInAlarmTigger(void)
{
//  PromptDoorLockedTigger();
}

void EventPlayLockedInAlarmRecovered(void)
{
//  PromptDoorLockedRecovered();
}

void EventPlayStartup(void)
{
//  PlayStartupAudio();
}

void EventPlayDeciceAutiLock(void)
{
//  PlayAutiLockAudio();
//  PromptDoorLockedTigger();
}

void EventPlayCardReplace(void)
{
//  PlayCardReplaceAudio();
//  PromptKeyHasBeenReplaced();
}

void EventPlayAudioOfAuthenticationFailure(void)
{
//  PromptAuthenticationError();
//  PlayPermissionDeniedAudio();
}

void EventPlayAudioOfOutOfDate(void)
{
//  PlayOutOfDateAudio();
//  PromptOutOfValidityPeriod();
}

void EventPlayAudioOfDeviceLocked(void)
{
//  PromptSystemLocked();
//  PlaySystemLockAudio();
}

void EventPlayLicenseExpiredSoundEffects(void)
{
//  PlayLicenseExpiredAudio();
//  PromptAuthenticationError();
}

void EventPlayExpirationReminder(uint8_t Days)
{
//  PlayExpirationReminderAudio(Days);
}

void EventPlayDeviceNotAuthorized(void)
{
//  PromptDeviceIsInitializing();
//  PlayDeviceInTheInitializedStateAudio();
}

void EventPlaySetParameterError(void)
{
//  PlaySettingStatusAudio(false);
//  PromptSetParameterError();
}

void EventPlaySetParameterSuccess(void)
{
//  PlaySettingStatusAudio(true);
//  PromptSetParameterSuccess();
}

void EventPlayExitVerificationMode(void)
{
//  PlayExitVerificationModeAudio();
}

void EventPlayVerifyUserPermissions(void)
{
//  PromptUserKeyedKeys();
//  PlayVerifyUserPermissionsAudio();
}

void EventPlayVerifyAdminPassword(void)
{
//  PlayVerifyAdminPasswordAudio();
}

void EventPlayEquipmentBusyStatus(void)
{
//  PlayEquipmentBusyStatusAudio();
}

void EventPlayRegisterUserCount(uint8_t Count)
{
//  PlayRegisterUserCountAudio(Count);
}

void EventPlayInitiateDocumentReceipt(void)
{
//  PromptOnlineRegisterUser();
//  PlayInitiateDocumentReceiptAudio();
}

void EventPlayLowBattery(void)
{
//  PromptLowPower();
//  PlayLowBatteryAudio();
}

void EventPlayUserExecutelockAction(void)
{
//  PlayUserExecuteDoorLockAudio();
}

void EventPlayDoorUnlock(void)
{
//  PromptDoorUnlock();
//  PlayCurrentLockStatusAudio(true);
}

void EventPlayDoorLock(void)
{
//  PromptDoorLock();
//  PlayCurrentLockStatusAudio(false);
}

void EventPlayDoorNormallyOpen(void)
{
//  PromptNormalOpenTigger();
//  PlayNormallyOpenStatueAudio(true);
}

void EventPlaySelfTestError(uint8_t ErrorCode)
{
//  PlaySelfTestErrorAudio(ErrorCode);
//  PromptDeviceSelfTestError(ErrorCode);
}

void EventPlayExitLocalRegister(void)
{
//  PlayExitLocalRegisterAudio();
}

void EventPlayLocalRegisterStatus(bool RegisterStatus)
{
//  PlayUserRegistrationStatusAudio(RegisterStatus);
//  (RegisterStatus == true) ? PromptKeyOperationSuccess() : PromptKeyOperationError();
}

bool EventGetNetworkQuality(void)
{
#if ((_NETWOK_FUNCTION_ENABLE_) && (_NETWOK_MODLE_TYPE_ != _RS485_MODULE_) && (_VOICE_PLAY_TYPE_ == _VOICE_PLAY_SPEAKER_))
#if _NETWOK_MODLE_TYPE_ == _ML307R_MODLE_
  uint8_t Quality = Ml307GetSignalStrength();
#elif _NETWOK_MODLE_TYPE_ == _TP1107_MODULE_
  uint8_t Quality = Tp1107GetWirelessQuality();
#endif

  PlayNetworkQualityAudio(Quality);
  return true;

#else
  return false;
#endif
}

void EventMotorPowerUpInitialization(void)
{
//  MotorPowerUpInitialization();
}

void EventExecuteDoorLock(void)
{
//  UpdateMotorActionStatus(MOTOR_LOCK);
}

void EventExecuteDoorUnlock(void)
{
//  UpdateMotorActionStatus(MOTOR_UNLOCKING);
}

void EventExecuteDoorNormalOpen(void)
{
//  UpdateMotorActionStatus(MOTOR_NORMALLY_OPEN);
}

void EventUpdateClutchStatus(uint8_t NewStatus)
{
//  UpdateMotorActionStatus(NewStatus);
}

bool EventDetermineIfLockOffPromptIsRequired(uint8_t UnlockType)
{
  if (UnlockType != LOG_GUEST_ROOM_CARD)
    return true;

  return false;
}

RegisterResult_t EventCreateNewKey(RegisterKeyInformation_t *pRegisterKeyInformationIn)
{
  uint8_t CreateReseult = 0;

  if (pRegisterKeyInformationIn != NULL)
  {
    KeyInformation_t NewKeyInformation = {0};

    NewKeyInformation.Count = pRegisterKeyInformationIn->Count;
    NewKeyInformation.KeyToken = pRegisterKeyInformationIn->KeyToken;
    NewKeyInformation.AuthenticationType = pRegisterKeyInformationIn->AuthenticationType;
    memcpy(NewKeyInformation.AuthenticationKey, pRegisterKeyInformationIn->AuthenticationKey, USER_AUTHENTICATION_KEY_LENGTH);

    NewKeyInformation.Date = pRegisterKeyInformationIn->Date;
    NewKeyInformation.EndTimestamp = pRegisterKeyInformationIn->EndTimestamp;
    NewKeyInformation.StartTimestamp = pRegisterKeyInformationIn->StartTimestamp;
    for (uint8_t i = 0; i < MAX_TIME_SLOTS; i++)
    {
      NewKeyInformation.TimePeriod[i].TimeCycle.StartHour = pRegisterKeyInformationIn->StartHour[i];
      NewKeyInformation.TimePeriod[i].TimeCycle.StartMinute = pRegisterKeyInformationIn->StartMinute[i];
      NewKeyInformation.TimePeriod[i].TimeCycle.EndHour = pRegisterKeyInformationIn->EndHour[i];
      NewKeyInformation.TimePeriod[i].TimeCycle.EndMinute = pRegisterKeyInformationIn->EndMinute[i];
    }

    CardholderCommandResult_t NewResult = NewCardholders(pRegisterKeyInformationIn->UserName, &NewKeyInformation);
    switch (NewResult)
    {
    case CARD_HOLDER_FULL:
      CreateReseult = REGISTER_USER_CARDHOLDER_IS_FULL;
      break;

    case KEY_ALREADY_EXISTS:
      CreateReseult = REGISTER_USER_KEY_ALREADY_EXISTS;
      break;

    case RECORD_SUCCESSFULLY:
      CreateReseult = REGISTER_USER_SUCCESS;
      break;

    case OVER_OF_SINGLE_USER_REGISTER_KEY:
      CreateReseult = REGISTER_USER_SINGLE_USER_LIMIT;
      break;

    default:
      CreateReseult = REGISTER_USER_ERROR;
      break;
    }
  }

  return CreateReseult;
}

UserAuthenticationResult_t EventVerifyAdministratorPassword(const void *pPasswordIn, uint8_t NumberOfPassword)
{
  char AdminPassword[NUMBER_OF_KEYBOARD_KEY] = {0};
  const char *pVerifyKeyValue = (const char *)pPasswordIn;

  GetSuperAdministratorPassword(AdminPassword);
  if (strstr(pVerifyKeyValue, AdminPassword) != NULL)
    return USER_AUTHENTICATION_SUCCESS;

  return USER_AUTHECTICATION_ERROR;
}

UserAuthenticationResult_t EventUserAuthentication(uint8_t KeyType, const void *pKeyValueIn, uint8_t NumberOfKey, uint8_t *pTranslatedKeyTypeOut, uint32_t *pKeyTokenOut, uint32_t *pEndTimesampOut)
{
  UserAuthenticationResult_t AuthenticationResult = USER_AUTHECTICATION_ERROR;

  {
    KeyInformation_t KeyInformation = {0};
    CardholderCommandResult_t VerifyResult = VerifyTheValidityOfTheTypedKey(KeyType, pKeyValueIn, NumberOfKey, &KeyInformation);

    switch (VerifyResult)
    {
    case AUTHENTICATION_SUCCESS:
    {
      AuthenticationResult = USER_AUTHENTICATION_SUCCESS;

      if (pKeyTokenOut != NULL)
      {
        *pKeyTokenOut = KeyInformation.KeyToken;
      }

      if (pEndTimesampOut != NULL)
      {
        *pEndTimesampOut = KeyInformation.EndTimestamp;
      }
    }
    break;

    case NOT_IN_THE_ALLOWED_TIME:
      AuthenticationResult = USER_OUT_OF_DATE;
      break;

    case CARDHOLDER_DISABLED:
      AuthenticationResult = USER_AUTHECTICATION_ERROR;
      break;

    default:
      AuthenticationResult = USER_AUTHECTICATION_ERROR;
      break;
    }
  }

  {
    if (pTranslatedKeyTypeOut != NULL)
    {
      switch (KeyType)
      {
      case CARD_AUTHENTICATION:
        *pTranslatedKeyTypeOut = LOG_PHYSICAL_CARD_NUMBER;
        break;

      case PASSWORD_AUTHENTICATION:
        *pTranslatedKeyTypeOut = LOG_USER_KEYSCANF_PASSWORD;
        break;

      case QRCODE_AUTHENTICATION:
        *pTranslatedKeyTypeOut = LOG_QR_CODE_SCANF;
        break;

      case FINGER_PRINTF_AUTHENTICATION:
        *pTranslatedKeyTypeOut = LOG_FINGER_SCANF;
        break;

      case FACE_ID_AUTHENTICATION:
        *pTranslatedKeyTypeOut = LOG_FACE_SCANF;
        break;

      case BLUETOOTH_VIRTUAL_CARD_AUTHENTICATION:
        *pTranslatedKeyTypeOut = LOG_BLUETOOTH_VIRTUAL_CARD_NUMBER;
        break;

      default:
        break;
      }
    }
  }

  return AuthenticationResult;
}

void EventWriteUserAuthenticationLogFile(const uint8_t KeyType, const uint8_t *pKeyValueIn, const uint32_t KeyToken, uint8_t Status)
{
  MemoryWriteUnlockLogMessage(KeyType, pKeyValueIn, KeyToken, Status);
}

void EventWriteDeviceStartupLogFile(void)
{
  WriteDeviceStartupLog();
}

void EventWriteFirmwareUpdateLogFile(void)
{
  uint16_t WriteTableId = WriteFirmwareUpgradeLog();
  if (WriteTableId != 0)
  {
    ProtocolUploadLogEventToHost(LOG_FIRMWARE_UPGRADE, 0, NULL);
  }
}

void EventWriteNormalOpenTiggerStatusLogFile(bool TiggerEn)
{
  uint16_t WriteTableId = WriteNormalOpenLog(TiggerEn);
  if (WriteTableId != 0)
  {
    ProtocolUploadLogEventToHost(LOG_NORMAL_OPEN, TiggerEn, NULL);
  }
}

void EventDeleteAllLogFile(void)
{
  InitialisationLogFile();
}

void EventRealTimePushOfUnlockEvent(uint8_t KeyType, const uint8_t *pKeyValueIn)
{
  if (pKeyValueIn != NULL)
  {
    ProtocolUploadLogEventToHost(KeyType, CARDHOLDER_AUTHENTICATION_SUCCESS, pKeyValueIn);
  }
}

void EventUpdateBluetoothRadio(void)
{
  BluetoothUpdateRadioPackage();
  printf("BluetoothUpdateRadioPackage \r\n");
}

void EventDeleteAllCardholder(void)
{
  InitialiseCardholderDirectory();
}

void EventRestoreDefaultUserParameters(void)
{
  RestoreDefaultUserParameters();
  MemoryUpdateDeviceParameters();
}

bool EventInitialisingDeviceParameters(void)
{
  return MemoryInitialisingdeviceparameters();
}

bool EventStartExternalValidation(void)
{
//  return SafetyStartUserAuthenticationTask();
}

void EventSafetyModuleIntoPowerDown(void)
{
//  SafetyStartForcedToGotoSleepTask();
}

void EventSendHeartbeatToServer(void)
{
  ProtocolSendHeartbeatToHost();
}

void EventResetMessageQueue(void)
{
  ProtocolResetMessageQueue();
}

void EventDisableRfidFunction(void)
{
  RfidDisableCardDecetionFunction();
}

void EventEnableRfidFunction(void)
{
  RfidEnableCardDecetionFunction();
}

void EventDisableKeyboardFunction(void)
{
//  Gtx31xDiableKeyboardFunction(0);
}

void EventEnableKeyboardFunction(void)
{
//  Gtx31xEnableKeyboardFunction();
}

void EventRfidExitCurrectMode(void)
{
  RfidExitCurrectTask();
}

bool EventCheckIfTheIndicatorLightIsOn(void)
{
//  return CheckIfTheIndicatorLightIsOn();
}

void EventActionBeforeSleep(void)
{
//  NetworkIntoPowerDown();
//  StopAllLightAlerts();
}

void EventSoftwareReset(void)
{
  SYS_ResetExecute();
}

void EventDisableAllInterrupt(void)
{
//  DisableAllSensorInSoucre();
}

void EventEnableAllInterrupt(void)
{
//  EnableAllSensorInSoucre();
}

uint8_t *EventMalloc(uint16_t MallocSize)
{
  return tmos_msg_allocate(MallocSize);
}

void EventFree(void *ptr)
{
  tmos_msg_deallocate((uint8_t *)ptr);
}

void EventStopTaskSchedule(void)
{
  tmos_stop_task(EventCenterTaskHandle, TASK_SCHEDULE);
}

void EventStartTaskSchedule(void)
{
  tmos_stop_task(EventCenterTaskHandle, TASK_SCHEDULE);
  tmos_set_event(EventCenterTaskHandle, TASK_SCHEDULE);
}

void EventStopScheduleTask(void)
{
  tmos_stop_task(EventCenterTaskHandle, SCHEDULED_TASK);
}

void EventDelayedStartScheduleTask(uint32_t DelayTime)
{
  tmos_stop_task(EventCenterTaskHandle, SCHEDULED_TASK);
  tmos_start_task(EventCenterTaskHandle, SCHEDULED_TASK, MS1_TO_SYSTEM_TIME(DelayTime));
}

void EventStartScheduleTaskNoWait(void)
{
  tmos_stop_task(EventCenterTaskHandle, SCHEDULED_TASK);
  tmos_set_event(EventCenterTaskHandle, SCHEDULED_TASK);
}

void EventStopDeviceRebootTask(void)
{
  tmos_stop_task(EventCenterTaskHandle, DEVICE_REBOOT_LISTER);
}

void EventDelayedStartDeviceRebootTask(uint32_t DelayTime)
{
  tmos_stop_task(EventCenterTaskHandle, DEVICE_REBOOT_LISTER);
  tmos_start_task(EventCenterTaskHandle, DEVICE_REBOOT_LISTER, MS1_TO_SYSTEM_TIME(DelayTime));
}

void EventStopRestoreFactoryTask(void)
{
  tmos_stop_task(EventCenterTaskHandle, RESTORE_RESULT_LISTER);
}

void EventDelayedStarRestoreFactoryTask(uint32_t DelayTime)
{
  tmos_stop_task(EventCenterTaskHandle, RESTORE_RESULT_LISTER);
  tmos_start_task(EventCenterTaskHandle, RESTORE_RESULT_LISTER, MS1_TO_SYSTEM_TIME(DelayTime));
}

void EventStartRestoreFactoryTaskNoWait(void)
{
  tmos_stop_task(EventCenterTaskHandle, RESTORE_RESULT_LISTER);
  tmos_set_event(EventCenterTaskHandle, RESTORE_RESULT_LISTER);
}

void EventStopIntoFirmwareUpdateTask(void)
{
  tmos_stop_task(EventCenterTaskHandle, SYSTEM_FIRMWARE_UPDATE);
}

void EventDelayedStartIntoFirmwareUpdateTask(uint32_t DelayTime)
{
  tmos_stop_task(EventCenterTaskHandle, SYSTEM_FIRMWARE_UPDATE);
  tmos_start_task(EventCenterTaskHandle, SYSTEM_FIRMWARE_UPDATE, MS1_TO_SYSTEM_TIME(DelayTime));
}

void EventStartIntoFirmwareUpdateTaskNoWait(void)
{
  tmos_stop_task(EventCenterTaskHandle, SYSTEM_FIRMWARE_UPDATE);
  tmos_set_event(EventCenterTaskHandle, SYSTEM_FIRMWARE_UPDATE);
}

void EventStopDeviceSelfTestTask(void)
{
  tmos_stop_task(EventCenterTaskHandle, DEVICE_SELF_TEST_LISTER);
}

void EventDelayedStartDeviceSelfTestTask(uint32_t DelayTime)
{
  tmos_stop_task(EventCenterTaskHandle, DEVICE_SELF_TEST_LISTER);
  tmos_start_task(EventCenterTaskHandle, DEVICE_SELF_TEST_LISTER, MS1_TO_SYSTEM_TIME(DelayTime));
}

void EventStartDeviceSelfTestTaskNoWait(void)
{
  tmos_stop_task(EventCenterTaskHandle, DEVICE_SELF_TEST_LISTER);
  tmos_set_event(EventCenterTaskHandle, DEVICE_SELF_TEST_LISTER);
}

bool ThrowEventToEventCenter(uint8_t Event, const void *pDataIn, uint8_t DataSize)
{
  if (DataSize <= EVENT_CARRYING_DATA_LENGTH)
  {
    if (DataSize > 0)
    {
      if (pDataIn == NULL)
        return false;
    }

    EventPacket_t *pEventMessage = (EventPacket_t *)tmos_msg_allocate(sizeof(EventPacket_t));
    if (pEventMessage != NULL)
    {
      pEventMessage->Type = Event;
      memcpy(pEventMessage->DataPacket, pDataIn, DataSize);
      tmos_msg_send(EventCenterTaskHandle, (uint8_t *)pEventMessage);

      return true;
    }
  }

  return false;
}

void EventCenterBoardInitialisation(EventCenterExternalInterfaces_t *pExternalInterfaces)
{
  EventCenterExternalInterfaces.TaskSchedule = pExternalInterfaces->TaskSchedule;
  EventCenterExternalInterfaces.ScheduledTask = pExternalInterfaces->ScheduledTask;
  EventCenterExternalInterfaces.DeviceRebootTask = pExternalInterfaces->DeviceRebootTask;
  EventCenterExternalInterfaces.RestoreFactoryTask = pExternalInterfaces->RestoreFactoryTask;
  EventCenterExternalInterfaces.FirmwareUpdateTask = pExternalInterfaces->FirmwareUpdateTask;
  EventCenterExternalInterfaces.DeviceSelfTestTask = pExternalInterfaces->DeviceSelfTestTask;
  EventCenterTaskHandle = TMOS_ProcessEventRegister(EventCenterTaskCallback);
}
